<template>
  <div class="task-course">
    <nav-header
      :headerTitle="`${courseText.name}任务`"
      :navBgColor="'#fff'"
      :isNext="true"
      :isNavBack="true"
      :isNedMsg="false"
      :isNextCourse="true"
      :courseType="courseType"
    ></nav-header>
    <div class="content" v-if="item">
      <div class="task-count-down">
        <task-count-down :pageName="'taskCourse'" @timeOver="timeOverOpt" :courseItem="itemCourse"></task-count-down>
      </div>
      <div class="task-progress">
        <task-progress :pageName="'taskCourse'" :failedReason="failedReason"></task-progress>
      </div>
      <ul class="task-step">
        <li class="step-detail">
          <div class="detail-title">
            <span class="red-dot"></span>
            <span class="title-text">{{courseText.oneStepTitle}}</span>
          </div>
          <div class="detail-text">{{courseText.oneStepContent}}</div>
          <div class="detail-fold" v-show="item.adType && item.adType === 1">
            <div class="fold-btn" @click="unfoldClick">{{foldText}}</div>
            <ul class="fold-order" v-show="isFoldOrderShow">
              <li v-for="(item, index) of subAdImgUrl" :key="'img' + index">
                <img :src="item+'?x-oss-process=image/resize,m_fill,h_188,w_188'" alt />
              </li>
              <div class="clearfix"></div>
            </ul>
          </div>
          <button class="detail-big-btn" @click.stop="shareTask">去{{courseText.name}}转发</button>
        </li>
        <li class="step-detail">
          <div class="detail-title">
            <span class="red-dot"></span>
            <span class="title-text">第二步：上传{{courseText.name}}截图</span>
          </div>
          <div class="detail-text">请上传您转发到{{courseText.name}}的截图，审核通过后，奖金自动到您的钱包。</div>
          <div class="detail-pic" v-show="item.adForwardImgUrl">
            <img :src="item.adForwardImgUrl+'?x-oss-process=image/resize,m_fill,h_180,w_180'" alt />
          </div>
          <button class="detail-big-btn" @click="readPic">{{submitTaskText}}</button>
        </li>
        <li class="step-detail">
          <div class="detail-item">
            <div class="detail-title">
              <span class="red-dot"></span>
              <span class="title-text">文字复制失败</span>
            </div>
            <button
              class="detail-small-btn"
              :data-clipboard-text="item.adContent"
              @click="copy('.detail-small-btn')"
              ref="copybtn"
            >复制</button>
            <div class="detail-text">如果文字复制失败，请点击上方按钮重新复制文字。</div>
          </div>
          <div class="detail-item" v-show="item.adType && item.adType === 1">
            <div class="detail-title">
              <span class="red-dot"></span>
              <span class="title-text">图片下载失败</span>
            </div>
            <button class="detail-small-btn" @click.stop="downLoadImgs">下载</button>
            <div class="detail-text">如果图片下载失败，请点击上方按钮重新下载图片。</div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import mixin from '@/utils/mixin'
import NavHeader from '@/components/NavHeader'
import TaskCountDown from '@/components/TaskCountDown'
import TaskProgress from '@/components/TaskProgress'
import shangchuan from '@/assets/images/shangchuan.png'
import { Dialog, Uploader, Toast } from 'vant'
import { setTimeout } from 'timers';
// import { mapActions } from 'vuex'

Vue.use(Uploader)

const wechatGro = {
  name: '微信群',
  oneStepTitle: '第一步：转发到200人以上的微信群',
  oneStepContent: '请把任务的文字和文章转发到大于200人的微信群。',
}
const friendGro = {
  name: '朋友圈',
  oneStepTitle: '第一步：转发朋友圈',
  oneStepContent: '请将任务的广告文字和文章转发到朋友圈。文章会自动填充，你只需要粘贴广告语即可。',
}
export default {
  name: 'taskCourse',
  mixins: [mixin],
  data () {
    return {
      wapConfig: {},
      inuniqueId: '',
      adId: '',
      forwardId: '',
      courseText: friendGro,
      failedReason: 0,
      item: JSON.parse(sessionStorage.getItem('taskItemString')),
      itemCourse: {},
      isFoldOrderShow: false,
      foldText: '查看图片顺序',
      submitTaskText: '上传截图',
      subAdImgUrl: [],
      courseType: 0,
      // uploadDisabled: true
    }
  },
  created () {
    // this.getInuniqueId()
  },
  mounted () {
    let query = this.$route.query;
    if (query) {
      this.inuniqueId = query.inuniqueId;
      this.adId = query.adId
    }
    this.getWapInfo();
    this.getTaskInfoByForwardId()
    // this.getCourseType()
  },
  methods: {
    // ...mapActions([
    //   'setTaskItemString'
    // ]),
    // 获取用户uniqueId
    // getInuniqueId () {
    //   if (localStorage.getItem('uniqueIdByInfluencer') === null) {
    //     this.inuniqueId = ''
    //     return false
    //   }
    //   this.inuniqueId = localStorage.getItem('uniqueIdByInfluencer')
    // },
    // 获取教程种类
    getCourseType (thisItem) {
      switch (thisItem.adCategory) {
        case 1:
          this.courseType = thisItem.adType === 1 ? 1 : 2
          break
        case 2:
          this.courseType = thisItem.adType === 2 ? 3 : 4
      }
    },
    // 截取图片顺序
    getSubAdImgUrl (itempra) {
      if (itempra.adType === 1) {
        if (itempra.adImgUrl) {
          this.subAdImgUrl = itempra.adImgUrl.split(',')
          // console.log(adImgUrls)
          return false
        }
      }
    },
    // 弹出收起图片顺序
    unfoldClick () {
      if (!this.isFoldOrderShow) {
        this.isFoldOrderShow = true
        this.foldText = '收起'
      } else {
        this.isFoldOrderShow = false
        this.foldText = '查看图片顺序'
      }
    },
    // 首次接任务下载弹窗显示
    showPopup (itempra) {
      if (this.item.id == itempra.id) {
        if (this.item.forwardAuditStatus === undefined) {
          // 首次接任务
          if (this.item.adType && this.item.adType === 1) {
            Dialog.alert({
              message: '任务广告文字将自动复制， 图片将自动下载到您的手机相册',
              cancelButtonText: '确定'
            }).then(() => {
              // 复制文字，下载图片，下载弹窗 待实现
              this.downLoadImgs()
              this.$refs.copybtn.click()
            });
          } else {
            Dialog.alert({
              message: '任务广告文字将自动复制',
              cancelButtonText: '确定'
            }).then(() => {
              // 复制广告文字
              this.$refs.copybtn.click()
              // this.test()
            });
          }
          sessionStorage.setItem('taskItemString', JSON.stringify(itempra))
        } else {
          sessionStorage.setItem('taskItemString', JSON.stringify(itempra))
          return false
        }
      }
    },
    // 初始化步骤文字，传出当前任务状态码
    getCourseText (itempra) {
      if (itempra.adCategory === 1) {
        this.courseText = friendGro
      } else {
        this.courseText = wechatGro
      }
      if (itempra.forwardAuditStatus === undefined || itempra.forwardAuditStatus === 0) {
        this.submitTaskText = '上传截图'
      } else {
        this.submitTaskText = '修改截图'
      }
      if (itempra.forwardAuditStatus && itempra.forwardAuditStatus === 3) {
        this.failedReason = itempra.forwardAuditStatus
        return false
      }
    },
    getWapInfo () {
      this.$http.post('/soft/getWapConfig', {}).then(
        res => {
          this.wapConfig = res.data;
        }
      )
    },
    // 获取任务步骤
    getTaskInfoByForwardId () {
      console.log(this.inuniqueId)
      console.log(this.adId)
      this.$http.post('/flowForward/getTaskInfoByForwardId', {
        uniqueId: this.inuniqueId,
        adId: this.adId
      }).then(
        res => {
          let resData = res.data;
          // this.setTaskItemString(JSON.stringify(resData))
          if ([2, 4, 5, 6].includes(resData.forwardAuditStatus)) {
            this.$router.replace({
              path: '/infMine/msgState',
              query: {
                inuniqueId: this.inuniqueId,
                adId: this.adId
              }
            })
            return false
          }
          this.getCourseType(resData)
          // console.log(resData)
          this.showPopup(resData);
          this.getSubAdImgUrl(resData);
          this.getCourseText(resData);
          this.item = resData;
          this.itemCourse = resData;

          sessionStorage.setItem('taskItemString', JSON.stringify(resData));
          if (!resData.forwardId) return;
          this.forwardId = resData.forwardId;
          // console.log(res.data)
        },
        err => {
          console.log(err)
        }
      )
    },
    // 下载图片
    downLoadImgs () {
      // 待实现
      let parmas = {
        imgUrl: this.subAdImgUrl
      };
      this.$bridge.callHandler('downloadImage', parmas, (res) => {
        if (!res) {
          Toast('图片下载失败，请重新下载')
        } else {
          Toast('图片下载完成，请尽快完成任务')
        }
      });
    },
    // 倒计时时间变零之后操作
    timeOverOpt (times) {
      if (times !== undefined) {
        // this.goUrl('/infIndex/index')
        this.$router.push({
          path: '/infMine/msgState',
          query: {
            inuniqueId: this.inuniqueId,
            adId: this.adId
          }
        })
      }
    },
    // 选择并预览图片，之后便上传图片提交任务
    readPic () {
      // this.uploadDisabled = true
      let meth
      if (this.item.adCategory === 1) {
        meth = 'momentsTaskImg'
      } else {
        meth = 'wxGroupTaskImg'
      }
      let parmas = {
        maxCount: 1,  //选择相册的最大数，若是相机拍照则只能为1
        sourceType: ['album'],
        method: meth
      };
      this.$bridge.callHandler('chooseImages', parmas, (res) => {
        // this.uploadDisabled = false
        if (!res) {
          this.submitTask(res)
        } else {
          // 预览图片
          let image = res.split(",")[0]
          // let imag = imagesArr[0]
          // let obj = [imag, this.adId]
          // sessionStorage.removeItem('imag')
          // sessionStorage.setItem('imag', obj)
          // this.imagesArr = imagesArr[0]
          // 上传图片并提交任务
          this.submitTask(image)
        }
      });
    },
    // 上传截图，提交任务
    submitTask (imags) {
      if (!imags) {
        Toast('图片上传失败！')
        return false
      }
      this.$http.post('/flowForward/submitTask', {
        forwardId: this.forwardId,
        adId: this.adId,
        forwardImgUrl: imags,
        uniqueId: this.inuniqueId
      }).then(
        res => {
          if (res.head.code === 200) {
            // let obj = [imags, this.adId]
            // sessionStorage.removeItem('imag')
            // sessionStorage.setItem('imag', obj)
            Toast('图片上传成功！')
            setTimeout(() => {
              window.location.reload()
            }, 800)
          } else if (res.head.code === 181) {
            Dialog.alert({
              message: '很抱歉，图片上传错误，任务已失败',
              confirmButtonText: '返回首页'
            }).then(() => {
              this.goUrl('/infIndex/index')
            })
          }
        },
        err => {
          console.log(err)
        }
      )
    },
    // 转发分享
    shareTask () {
      let adInfo = this.itemCourse;
      console.log(adInfo);
      // let sharelink = `${window.location.origin}/#/adIndex/articleDetailWX?articleId=${adInfo.adArticleId}&articleTitle=${adInfo.adArticleTitle}&uniqueId=${this.inuniqueId}&shareUniqueId=${adInfo.uniqueId}` 
      let _wapConfig = this.wapConfig;
      let sharelink = `${_wapConfig.articleDetailDomain}/#/adIndex/articleDetailWX/${adInfo.adArticleId}/${adInfo.adArticleTitle}/${this.inuniqueId}/${adInfo.uniqueId}`
      let adType = adInfo.adType; //adType--1-图文广告  2-文章广告
      let parmas;
      if (adInfo.adCategory == 1) {
        // adCategory--1朋友圈 2微信朋友微信群
        if (adType == 1) {
          parmas = {};
          this.$bridge.callHandler('switchWechat', parmas, (res) => {
            console.log(res)
          });
        } else {
          parmas = {
            title: adInfo.adArticleTitle, // 分享标题 
            link: sharelink, // 分享链接 
            imgUrl: adInfo.adArticleThumbnailsUrl, // 分享图标
            shareType: "1"
          };
          console.log(parmas)
          this.$bridge.callHandler('shareTimeline', parmas, (res) => {
            console.log(res);
          });
        }
      } else {
        //adCategory-- 2微信朋友微信群
        if (adType == 1) {
          parmas = {
            imgUrl: adInfo.adImgUrl, // 分享图标,多图
            shareType: "2"
          };
        } else {
          parmas = {
            title: adInfo.adArticleTitle, // 分享标题
            desc: adInfo.adArticleTitle, // 分享描述
            link: sharelink, // 分享链接 
            imgUrl: adInfo.adArticleThumbnailsUrl, // 分享图标
            shareType: "1"
          };
        }
        console.log(parmas)
        this.$bridge.callHandler('shareAppMessage', parmas, (res) => {
          console.log(res)
        });
      }
    }
  },
  components: {
    NavHeader,
    TaskCountDown,
    TaskProgress
  }
}
</script>

<style scoped lang="scss">
@import '~@/assets/css/common.scss';
.task-course {
  width: 100%;
  height: 100%;
  padding: 0 32px;
  box-sizing: border-box;
  .content {
    width: 100%;
    height: 100%;
    margin-top: 112px;
    // .task-list {
    // }
    .task-count-down {
      margin-bottom: 24px;
    }
    .task-step {
      .step-detail {
        width: 686px;
        background: rgba(237, 237, 237, 1);
        border-radius: 16px;
        box-sizing: border-box;
        padding: 32px;
        margin-bottom: 24px;
        .detail-item {
          margin-bottom: 48px;
          position: relative;
        }
        .detail-title {
          width: 100%;
          height: 48px;
          display: flex;
          position: relative;
          margin-bottom: 16px;
          .red-dot {
            border-radius: 100%;
            width: 16px;
            height: 16px;
            background: rgba(254, 37, 37, 1);
            box-shadow: 0px 2px 6px 0px rgba(254, 37, 37, 0.5);
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
          }
          .title-text {
            font-size: 34px;
            font-family: PingFangSC-Medium;
            font-weight: 500;
            color: rgba(48, 49, 51, 1);
            line-height: 48px;
            box-sizing: border-box;
            padding-left: 32px;
          }
        }
        .detail-small-btn {
          width: 120px;
          height: 50px;
          background: rgba(254, 37, 37, 1);
          border-radius: 34px;
          font-size: 28px;
          font-family: PingFangSC-Medium;
          font-weight: 500;
          color: rgba(255, 255, 255, 1);
          line-height: 40px;
          position: absolute;
          top: 0;
          right: 0;
        }
        .detail-text {
          font-size: 30px;
          font-family: PingFangSC-Regular;
          font-weight: 400;
          color: rgba(48, 49, 51, 1);
          line-height: 42px;
          margin-bottom: 24px;
        }
        .detail-fold {
          margin-bottom: 24px;
          // position: relative;
          .fold-btn {
            height: 48px;
            font-size: 34px;
            font-family: PingFangSC-Regular;
            font-weight: 400;
            color: rgba(96, 101, 124, 1);
            line-height: 48px;
            margin-bottom: 24px;
          }
          .fold-order {
            width: 594px;
            margin-bottom: 24px;
            position: relative;
            li {
              width: 188px;
              height: 188px;
              background-color: #ccc;
              text-align: center;
              overflow: hidden;
              margin-left: 10px;
              display: block;
              float: left;
              // margin
              position: relative;
              margin-bottom: 10px;
              img {
                // width: 188px;
                height: 188px;
                @include pic-center;
              }
            }
          }
        }
        .detail-pic {
          height: 180px;
          width: 180px;
          margin-bottom: 32px;
          img {
            height: 180px;
            width: 180px;
          }
        }
        .detail-big-btn {
          width: 622px;
          height: 88px;
          background: rgba(254, 37, 37, 1);
          border-radius: 44px;
          font-size: 32px;
          font-family: PingFangSC-Medium;
          font-weight: 500;
          color: rgba(255, 255, 255, 1);
          line-height: 45px;
        }
      }
    }
  }
}
</style>
